import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import { GspEventType } from '@app-nextmesh/types/document';
import { events } from '@app-nextmesh/utils';
import realTimeCurveOption from '@app-nextmesh/widgets/RightNavigation/RealTimeCurve/Curve';
import { Col, Row } from 'antd';
import * as echarts from 'echarts';
import { useEffect, useRef, useState } from 'react';
import BaseForm from '../BaseForm';
import { IProps } from './types';

export default function TaskMonitorForm({ data: initData, onClose }: IProps) {
  const [showText, setShowText] = useState(false);
  const [showCharts, setShowCharts] = useState(false);
  const projectInfo = useProjectStore((state) => state.projectInfo);
  const chartsRef = useRef<HTMLDivElement>(null);
  const echartsRef = useRef<echarts.ECharts>(null);
  const [lineChart, setLineChart] = useState({});
  const contentRef = useRef<HTMLParagraphElement>(null);

  useEffect(() => {
    if (!chartsRef.current && !showCharts) {
      return () => {};
    }
    echartsRef.current = echarts.init(chartsRef.current);
    const onResize = () => {
      echartsRef.current.resize();
    };
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
    };
  }, [chartsRef.current, showCharts]);
  useEffect(() => {
    if (!echartsRef.current) {
      return;
    }
    const chart = echartsRef.current;
    const curve: any = realTimeCurveOption(chart, lineChart);
    chart.setOption(curve.option);
  }, [echartsRef, lineChart]);
  useEffect(() => {
    documentV2.getTaskMonitorData(initData.formData.uuid).then(initMonitor);
  }, [initData.formData]);
  useEffect(() => {
    events.on(GspEventType.taskmonitor, initMonitor);
    return () => {
      events.off(GspEventType.taskmonitor, initMonitor);
    };
  }, [initData.formData, contentRef.current]);

  const initMonitor = (rsp) => {
    const text = rsp.data?.log ?? rsp.log;
    const chart = rsp.data?.convergence_history ?? rsp.convergence_history;
    const formObject = initData.formData;
    // 如果不是该任务的数据，直接返回（rsp.uuid为undefined，默认就是）
    if (rsp.uuid !== undefined && formObject.uuid !== rsp.uuid) {
      return;
    }
    if (text) {
      setShowText(true);
      setTimeout(() => {
        initTaskmonitor(text);
      }, 100);
    } else {
      if (contentRef.current !== null) {
        contentRef.current.innerHTML = '';
      }
      setShowText(false);
    }
    // 判断chart是否为空，或空对象
    if (chart && Object.keys(chart).length > 0) {
      setShowCharts(true);
      setLineChart(chart);
    } else {
      setShowCharts(false);
      setLineChart({});
    }
  };
  function handleClose() {
    onClose();
  }
  const initTaskmonitor = async (text: string) => {
    if (text === '' || contentRef.current === null) {
      return;
    }
    const lines = text.split('\n');
    contentRef.current.innerHTML = lines
      .map((line, index) => `<p>${index + 1}. ${line}</p>`)
      .join('');
  };
  return (
    <>
      <BaseForm
        disabled={projectInfo.readonly}
        title={'监控'}
        hideConfirm={false}
        customStyle={{ width: '1500px' }}
        titleEditable={false}
        onClose={handleClose}>
        <Row>
          <Col span={showCharts ? 9 : 24}>
            {showText && (
              <div
                style={{
                  zIndex: 200,
                  height: '655px',
                  overflowY: 'visible',
                  marginRight: '-110px',
                }}>
                <pre className='line-numbers'>
                  <p ref={contentRef}></p>
                </pre>
              </div>
            )}
          </Col>
          <Col span={showText ? 9 : 24}>
            {showCharts && (
              <div
                style={{
                  position: 'fixed',
                  height: '655px',
                  width: '800px',
                  marginLeft: '110px',
                }}>
                <div
                  ref={chartsRef}
                  style={{
                    height: '100%',
                    background: 'transparent',
                  }}></div>
                <div
                  style={{
                    position: 'absolute',
                    top: '10px',
                    right: '10px',
                    width: '100vh',
                  }}></div>
              </div>
            )}
          </Col>
        </Row>
      </BaseForm>
    </>
  );
}
